/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.api.utils;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.api.InternalSvrContainer;
import lombok.var;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import java.lang.reflect.Method;

/**
 * @author Leon Huo
 */
public class RpcAppContextUtils {

    public static <T> T getBean(Class<T> clazz) {
        return SpringBeanUtils.getBean(clazz);
    }

    /**
     * 是否注册成了bean
     *
     * @return
     */
    public static boolean isRegisteredBean(Class t) {
        try {
            return SpringBeanUtils.getBean(t) != null;
        } catch (NoSuchBeanDefinitionException e) {
            return false;
        }
    }

    /**
     * 根据方法名获取方法，不保证方法参数信息是否正确
     *
     * @param type
     * @param name
     * @return
     */
    public static Method getMethodByName(Class type, String name) {
        Method med = null;
        var meds = type.getMethods();
        for (var m : meds) {
            if (m.getName().equalsIgnoreCase(name)) {
                med = m;
                break;
            }
        }

        return med;
    }

    /**
     * 获取类型实例
     *
     * @param t 类型
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static Object getTypeInstance(Class interfaceType, Class t) throws IllegalAccessException, InstantiationException {
        Object instance = null;
        if (RpcAppContextUtils.isRegisteredBean(interfaceType)) {
            instance = RpcAppContextUtils.getBean(interfaceType);
        } else {
            instance = InternalSvrContainer.getService(interfaceType);
        }

        return instance;
    }

}

